package com.swj.modules.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swj.common.core.constant.UserConstants;
import com.swj.common.core.exception.ServiceException;
import com.swj.common.core.exception.auth.NotPermissionException;
import com.swj.common.core.model.SysDept;
import com.swj.common.core.model.SysUser;
import com.swj.common.core.utils.SpringUtil;
import com.swj.common.core.utils.SysStringUtil;
import com.swj.common.core.utils.bean.BeanValidators;
import com.swj.common.datascope.annotation.DataScope;
import com.swj.common.security.utils.SecurityUtil;
import com.swj.modules.system.mapper.SysUserMapper;

import com.swj.modules.system.model.SysUserQueryVO;
import com.swj.modules.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author Sans
 * @Description 系统用户业务实现
 * @CreateTime 2019/6/14 15:57
 */
@Service("sysUserService")
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class SysUserServiceImpl
        extends ServiceImpl<SysUserMapper, SysUser>
        implements ISysUserService {

    @Resource
    private SysUserMapper userMapper;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysDeptService deptService;

    @Resource
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;

    /**
     * 根据用户名查询实体
     *
     * @param userName 用户名
     * @return SysUserEntity 用户实体
     * @author swj
     * @CreateTime 2019/6/14 16:30
     */
    @Override
    public SysUser selectUserAndRolesAndPermissonsByName(String userName) {
        return userMapper.selectUserByName(userName);
    }

    /**
     * 根据用户名查询实体
     *
     * @param userName 用户名
     * @return SysUserEntity 用户实体
     * @author Sans
     * @CreateTime 2019/6/14 16:30
     */
    @Override
    public SysUser selectUserByName(String userName) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getUserName, userName);
        return userMapper.selectOne(queryWrapper);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * 三表联查 包含部门的信息和角色信息
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(String userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(SysUser user) {
        String userId = SysStringUtil.isNull(user.getId()) ? "-1" : user.getId();
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", user.getUserName())
                .last("limit 1");
        SysUser info = userMapper.selectOne(queryWrapper);
        if (SysStringUtil.isNotNull(info) && !info.getId().equals(userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }



    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return 是否唯一
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        String userId = SysStringUtil.isNull(user.getId()) ? "-1" : user.getId();
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone_number", user.getPhoneNumber())
                .last("limit 1");
        SysUser info = userMapper.selectOne(queryWrapper);
        if (SysStringUtil.isNotNull(info) && !info.getId().equals(userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return 是否唯一
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        String userId = SysStringUtil.isNull(user.getId()) ? "-1" : user.getId();
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", user.getEmail())
                .last("limit 1");
        SysUser info = userMapper.selectOne(queryWrapper);
        if (SysStringUtil.isNotNull(info) && !info.getId().equals(userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insert(user);
        // 新增用户与角色管理
        roleService.insertUserRoleRelation(user);
        // 新增用户与岗位管理
        postService.insertUserPostRelation(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insert(user) > 0;
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUserQueryVO user) {
        List<SysUser> userList = userMapper.selectList(getQueryWrapper(user));
        formatRecodrs(userList);
        return userList;
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public Page<SysUser> selectUserPage(SysUserQueryVO user) {
        Page<SysUser> page = new Page<>(user.getPageNum(), user.getPageSize());
        Page<SysUser> userPage = userMapper.selectPage(page, getQueryWrapper(user));
        formatRecodrs(userPage.getRecords());
        return userPage;
    }

    private QueryWrapper<SysUser> getQueryWrapper(SysUserQueryVO user) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(SysStringUtil.isNotBlank(user.getUserName()), "user_name", user.getUserName())
                .like(SysStringUtil.isNotBlank(user.getPhoneNumber()), "phone_number", user.getPhoneNumber())
                .eq(SysStringUtil.isNotBlank(user.getDeptId()) && !"100".equals(user.getDeptId()), "dept_id", user.getDeptId())
                .eq(SysStringUtil.isNotBlank(user.getStatus()), "status", user.getStatus())
                .gt(Objects.nonNull(user.getBeginTime()), "create_time", user.getBeginTime())
                .lt(Objects.nonNull(user.getEndTime()), "create_time", user.getEndTime())
                .orderByDesc("update_time")
                .orderByDesc("status");
        return queryWrapper;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     * 如果被操作的用户是admin,抛出异常
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (SysStringUtil.isNotNull(user.getId()) && SysUser.isAdmin(user.getId())) {
            throw new NotPermissionException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(String userId) {
        if (!SysUser.isAdmin(SecurityUtil.getUserId())) {
            SysUserQueryVO user = new SysUserQueryVO(userId);
            user.setId(userId);
            List<SysUser> users = SpringUtil.getAopProxy(this).selectUserList(user);
            if (SysStringUtil.isEmpty(users)) {
                throw new NotPermissionException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(SysUser user) {
        // 删除用户与角色关联
        roleService.deleteUserRoleRelation(user);
        // 新增用户与角色管理
        roleService.insertUserRoleRelation(user);
        // 删除用户与岗位关联
        postService.deleteUserPostRelation(user);
        // 新增用户与岗位管理
        postService.insertUserPostRelation(user);
        int num = userMapper.updateById(user);
        return num > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(String[] userIds) {
        for (String userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        roleService.deleteUserRoleRelations(userIds);
        // 删除用户与岗位关联
        postService.deleteUserPostRelations(userIds);
        //批量删除用户信息
        return userMapper.deleteBatchIds(Arrays.asList(userIds));
    }

    private void formatRecodrs(List<SysUser> list) {
        Set<String> deptIdSet = list.stream().map(SysUser::getDeptId)
                .filter(SysStringUtil::isNotEmpty)
                .collect(Collectors.toSet());
        Set<String> userIds = list.stream().map(SysUser::getId).collect(Collectors.toSet());

        List<SysDept> deptList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userIds)) {
            deptList = deptService.listByIds(deptIdSet);
        }
        Map<String, SysDept> deptMap = deptList.stream().collect(Collectors.toMap(SysDept::getId, v -> v, (v1, v2) -> v1));

        list.forEach(item -> {
            item.setDept(deptMap.get(item.getDeptId()));
            item.setPost(postService.selectPostByUserId(item.getId()));
            item.setRoles(new HashSet<>(roleService.selectRoleByUserId(item.getId())));
        });
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (SysStringUtil.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = selectUserByName(user.getUserName());
                if (SysStringUtil.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtil.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(user);
                    checkUserDataScope(user.getId());
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}